package com.jy.appmarket.screenlock;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.android.calculator.CalculatorActivity;
import com.android.corestat.utils.SimUtil;
import com.imbryk.viewpager.LoopViewPager;
import com.jy.app.market.apk.type.LinkType;
import com.jy.app.market.idata.data.Link;
import com.jy.app.market.idata.data.LockscreenCfg;
import com.jy.app.market.idata.data.LockscreenCfgItem;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.activity.AppDetailActivity;
import com.jy.appmarket.activity.CardPageActivity;
import com.jy.appmarket.activity.LoadingActivity;
import com.jy.appmarket.activity.PhoneEssentialActivity;
import com.jy.appmarket.activity.WebViewActivity;
import com.jy.appmarket.screenlock.activity.BeautifulLockerSettingActivity;
import com.jy.appmarket.screenlock.activity.InitSettingDialogActivity;
import com.jy.appmarket.screenlock.adapter.ShortcutAppMainLockAdapter;
import com.jy.appmarket.screenlock.adapter.ShortcutAppMainLockAdapter.OnShortcutListener;
import com.jy.appmarket.screenlock.model.AppModel;
import com.jy.appmarket.screenlock.model.MessageModel;
import com.jy.appmarket.screenlock.prefs.LockPrefs;
import com.jy.appmarket.screenlock.prefs.LockPrefs.PasswordType;
import com.jy.appmarket.screenlock.receiver.LockScreenReceiver;
import com.jy.appmarket.screenlock.service.LockerService;
import com.jy.appmarket.screenlock.service.SystemNotificationListener;
import com.jy.appmarket.screenlock.service.SystemNotificationService;
import com.jy.appmarket.screenlock.utils.ImageUtils;
import com.jy.appmarket.screenlock.utils.LockScreenConfig;
import com.jy.appmarket.screenlock.utils.XiaomiUtils;
import com.jy.appmarket.screenlock.view.LockNumberView;
import com.jy.appmarket.screenlock.view.LockNumberView.OnLockNumberListener;
import com.jy.appmarket.screenlock.view.MessageView;
import com.jy.appmarket.screenlock.view.MessageView.MessageListener;
import com.jy.appmarket.screenlock.view.PatternPasswordView;
import com.jy.appmarket.screenlock.view.PatternPasswordView.OnPatternViewListener;
import com.jy.appmarket.screenlock.view.PatternPasswordView.PatternViewResult;
import com.jy.appmarket.screenlock.view.ProgressView;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.Config;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.NetTools;
import com.jy.appmarket.utils.ResourceUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.service.notification.StatusBarNotification;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.SlidingDrawer.OnDrawerScrollListener;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 类说明：
 * 
 * @author kalui.huang
 * @date 2015-3-10
 * @version 1.0
 */
public class MainLockViewManager implements OnClickListener {

	protected static final String TAG = "MainLockViewManager";
	private static final int LINK_ICON_NORMAL = 0;
	private static final int LINK_ICON_PRESSED = 1;
	private static final int LINK_ICON_SELECTED = 2;

	private View mContentView;
	private Context mContext;

	private SlidingDrawer mSlidingDrawer;
	private RelativeLayout mLockHandlerLy;
	private ImageView mSlidingSwitchIv;
	private GridView mSlidingContent;
	private ShortcutAppMainLockAdapter mAdapter;
	private LoopViewPager mWallpaperViewpager;
	private ImageView mUnlockHandlerIv;

	private static Handler mHandler = new Handler(Looper.getMainLooper());
	private List<AppModel> mList;
	private MyReceiver mReceiver;
	private TextView mElectricQuantityTv;
	private ImageView mChargingIv;
	private ProgressView mChargingPv;
	private TextView mDateTimeTv;
	private TextView mDateWeekTv;
	private MessageView mMessageView;
	private ImageView mUnlockLinkIv;
	private ImageView mUnlockIv;
	private ImageView mArrowLeftIv;
	private ImageView mArrowRightIv;
	private RelativeLayout mMainLockScreenLy;
	private RelativeLayout mMainLockBottomLy;
	private PopupWindow mPasswdWindow;
	private PasswordType mPasswordType;

	private PowerManager.WakeLock mWakeLock;
	private PowerManager pm;
	private static DevicePolicyManager mPolicyManager;
	private static ComponentName mComponentName;
	private Handler lockHandler = new MyHandler();
	private ImageUtils mImageUtils;
	private Link mLink;
	private String mLinkIconNPath;
	private String mLinkIconPPath;
	private String mLinkIconSPath;
	private static int mCurrentPageIndex = 0;
	private boolean isDefaultWallpaper = true;
	private List<LockscreenCfgItem> mWallpaperItems;

	private boolean mIsLightOpen;
	private Camera mCamera;
	private Vibrator mVibrator;
	private long[] mPattern = { 100, 200 };
	private String mTopActivityName;

	public enum MainLockResult {
		UNLOCK, COMFIRE_PASSWORD
	}

	private LinearLayout mSlidingHandler;
	private OnSlidingDrawerOpenListener mDrawerListener;
	private Runnable mUnLockRunnable = null;
	private LockScreenManager mLockManager;

	public void setOnSlidingDrawerOpenListener(OnSlidingDrawerOpenListener listener) {
		mDrawerListener = listener;
	}

	public MainLockViewManager(Context context, boolean isWallpaperShowPhrase) {
		mContext = context;
		pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		// 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
		mWakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
				"wake_lock");
		// 获取设备管理服务
		mPolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
		mComponentName = new ComponentName(context, LockScreenReceiver.class);
		mImageUtils = new ImageUtils();
		mLockManager = LockScreenManager.getInstance(mContext);
		mVibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
		ComponentName topCompnent = getRunningTopPkgApp(mContext);
		if (topCompnent != null) {
			mTopActivityName = topCompnent.getClassName();
		}

		initView();
		initData();
	}

	public View getMainLockView() {
		return mContentView;
	}

	private void initView() {
		mContentView = LayoutInflater.from(mContext).inflate(R.layout.fragment_main_lock, null);
		mWallpaperViewpager = mContentView.findViewById(R.id.wallpaper_viewpager);
		mMainLockScreenLy = mContentView.findViewById(R.id.main_lock_screen_layout);
		mMainLockBottomLy = mContentView.findViewById(R.id.main_lock_bottom_lay);
		mUnlockHandlerIv = mContentView.findViewById(R.id.unlock_handler);
		mUnlockLinkIv = mContentView.findViewById(R.id.main_lock_more_iv);
		mUnlockIv = mContentView.findViewById(R.id.main_lock_unlock_iv);
		mSlidingDrawer = mContentView.findViewById(R.id.main_lock_sliding_drawer);
		mLockHandlerLy = mContentView.findViewById(R.id.main_lock_handler_lay);
		mMessageView = mContentView.findViewById(R.id.main_lock_message_view);
		mSlidingSwitchIv = mContentView.findViewById(R.id.sliding_switch_iv);
		mSlidingContent = mContentView.findViewById(R.id.sliding_content);
		mSlidingHandler = mContentView.findViewById(R.id.sliding_handler);
		mElectricQuantityTv = mContentView.findViewById(R.id.electric_quantity);
		mChargingIv = mContentView.findViewById(R.id.charging_image);
		mChargingPv = mContentView.findViewById(R.id.battery_charging_progress);
		mDateTimeTv = mContentView.findViewById(R.id.date_time);
		mDateWeekTv = mContentView.findViewById(R.id.date_week);
		mArrowLeftIv = mContentView.findViewById(R.id.main_lock_arrow_left);
		mArrowRightIv = mContentView.findViewById(R.id.main_lock_arrow_right);
		mContentView.findViewById(R.id.main_lock_setting_btn).setOnClickListener(this);

		initWallpaperViewpager();
		initUnlockHandler();
		initSlidingDrawer();
		initMessageView();
		initPasswdView();

		registerReceiver();
	}

	private void initWallpaperViewpager() {
		mWallpaperViewpager.setAdapter(getWallpaperAdapter());
		if (mCurrentPageIndex >= mWallpaperItems.size()) {
			mCurrentPageIndex = 0;
		}
		mWallpaperViewpager.setCurrentItem(mCurrentPageIndex);
		showLinkIcon(mCurrentPageIndex);

		mWallpaperViewpager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				showLinkIcon(position);
				mCurrentPageIndex = position;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

		mWallpaperViewpager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (mWallpaperItems.size() > 1) {
						mArrowLeftIv.setVisibility(View.VISIBLE);
						mArrowRightIv.setVisibility(View.VISIBLE);
					}
					break;
				case MotionEvent.ACTION_UP:
					if (mWallpaperItems.size() > 1) {
						mArrowLeftIv.setVisibility(View.GONE);
						mArrowRightIv.setVisibility(View.GONE);
					}
					v.performClick();
					break;
				}
				return false;
			}
		});
	}

	private void initUnlockHandler() {
		mUnlockHandlerIv.setOnTouchListener(new OnTouchListener() {
			float originX = -1;
			int unlockLeft;
			int unlockRight;
			int unLockRadius;
			int lastX;
			int center;
			int radius;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					changeLinkIconStatus(LINK_ICON_PRESSED);
					lastX = (int) event.getRawX();
					if (originX == -1) {
						originX = v.getX();
					}
					unlockLeft = (mUnlockLinkIv.getLeft() + mUnlockLinkIv.getRight()) / 2;
					unlockRight = (mUnlockIv.getLeft() + mUnlockIv.getRight()) / 2;
					unLockRadius = mUnlockIv.getWidth() / 2;
					radius = v.getWidth() / 2;
					center = v.getLeft() + radius;
					break;
				case MotionEvent.ACTION_MOVE:
					int dx = (int) event.getRawX() - lastX;
					if (Math.abs(dx) < 8) {
						break;
					}
					lastX = (int) event.getRawX();
					center = (int) (v.getX() + dx + radius);

					if (center - unlockLeft < radius + unLockRadius - 10) {
						if (dx > 0) {
							center = (int) event.getRawX();
							if (center > unlockLeft) {
								v.setX(center - radius);
								if (!isDefaultWallpaper) {
									mUnlockLinkIv.setImageBitmap(mImageUtils.getBitmapDecodeFile(mLinkIconPPath));
								} else {
									mUnlockLinkIv.setImageResource(ResourceUtil.getDrawable(mContext, mLinkIconPPath));
								}
								mUnlockHandlerIv.setBackgroundResource(R.drawable.main_lock_handler_p);
							}
							break;
						} else if (dx < 0) {
							center = unlockLeft;
						}
					} else if (unlockRight - center < radius + unLockRadius - 10) {
						if (dx < 0) {
							center = (int) event.getRawX();
							if (center < unlockRight) {
								v.setX(center - radius);
								mUnlockIv.setImageResource(R.drawable.main_lock_unlock_p);
								mUnlockHandlerIv.setBackgroundResource(R.drawable.main_lock_handler_p);
							}
							break;
						} else if (dx > 0) {
							center = unlockRight;
						}
					}

					if (center <= unlockLeft) {
						v.setX(unlockLeft - radius);
						if (!isDefaultWallpaper) {
							mUnlockLinkIv.setImageBitmap(mImageUtils.getBitmapDecodeFile(mLinkIconSPath));
						} else {
							mUnlockLinkIv.setImageResource(ResourceUtil.getDrawable(mContext, mLinkIconSPath));
						}
						mUnlockHandlerIv.setBackgroundResource(R.drawable.main_lock_handler_p);
						break;
					} else if (center >= unlockRight) {
						v.setX(unlockRight - radius);
						mUnlockIv.setImageResource(R.drawable.main_lock_unlock_s);
						mUnlockHandlerIv.setBackgroundResource(R.drawable.main_lock_handler_p);
						break;
					}
					v.setX(center - radius);

					break;
				case MotionEvent.ACTION_UP:
					if (center > unlockLeft && center < unlockRight) {
						v.setX(originX);
						changeLinkIconStatus(LINK_ICON_NORMAL);
					} else if (center >= unlockRight) {
						mHandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								unlock(getInitSettingRunnable(), false);
								mUnlockHandlerIv.setX(originX);
								changeLinkIconStatus(LINK_ICON_NORMAL);
							}
						}, 30);
					} else if (center <= unlockLeft) {
						mHandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								unlock(getLinkRunnable(mLink), false);
								mUnlockHandlerIv.setX(originX);
								changeLinkIconStatus(LINK_ICON_NORMAL);
							}
						}, 30);
					}
					v.performClick();

					break;
				}
				return true;
			}
		});
	}

	private void changeLinkIconStatus(int status) {
		switch (status) {
		case LINK_ICON_NORMAL:
			if (!isDefaultWallpaper) {
				mUnlockLinkIv.setImageBitmap(mImageUtils.getBitmapDecodeFile(mLinkIconNPath));
			} else {
				mUnlockLinkIv.setImageResource(ResourceUtil.getDrawable(mContext, mLinkIconNPath));
			}
			mUnlockHandlerIv.setBackgroundResource(R.drawable.main_lock_handler_n);
			mUnlockIv.setImageResource(R.drawable.main_lock_unlock_n);
			break;
		case LINK_ICON_PRESSED:
			if (!isDefaultWallpaper) {
				mUnlockLinkIv.setImageBitmap(mImageUtils.getBitmapDecodeFile(mLinkIconPPath));
			} else {
				mUnlockLinkIv.setImageResource(ResourceUtil.getDrawable(mContext, mLinkIconPPath));
			}
			mUnlockHandlerIv.setBackgroundResource(R.drawable.main_lock_handler_p);
			mUnlockIv.setImageResource(R.drawable.main_lock_unlock_p);
			break;
		case LINK_ICON_SELECTED:
			if (!isDefaultWallpaper) {
				mUnlockLinkIv.setImageBitmap(mImageUtils.getBitmapDecodeFile(mLinkIconSPath));
			} else {
				mUnlockLinkIv.setImageResource(ResourceUtil.getDrawable(mContext, mLinkIconSPath));
			}
			mUnlockHandlerIv.setBackgroundResource(R.drawable.main_lock_handler_p);
			mUnlockIv.setImageResource(R.drawable.main_lock_unlock_s);
			break;
		}
	}

	@SuppressWarnings("deprecation")
	private void initSlidingDrawer() {
		mSlidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			public void onDrawerOpened() {
				mLockHandlerLy.setVisibility(View.GONE);
				mSlidingSwitchIv.setImageResource(R.drawable.main_lock_sliding_down);
				mSlidingHandler.setBackgroundResource(R.drawable.fifth_transparent);
				if (mDrawerListener != null) {
					mDrawerListener.onSlidingDrawerChange(true);
				}
				LogUtil.i("slidingDraw", "open");
			}
		});
		mSlidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {

			public void onDrawerClosed() {
				mLockHandlerLy.setVisibility(View.VISIBLE);
				mSlidingHandler.setBackgroundResource(R.drawable.transparent);
				mSlidingSwitchIv.setImageResource(R.drawable.main_lock_sliding_up);
				if (mDrawerListener != null) {
					mDrawerListener.onSlidingDrawerChange(false);
				}
				LogUtil.i("slidingDraw", "close");
			}
		});

		mSlidingDrawer.setOnDrawerScrollListener(new OnDrawerScrollListener() {

			@Override
			public void onScrollStarted() {
				mSlidingHandler.setBackgroundResource(R.drawable.fifth_transparent);
				LogUtil.i("slidingDraw", "start");
			}

			@Override
			public void onScrollEnded() {
				LogUtil.i("slidingDraw", "end");
				Thread watchMovingThread = new Thread(new Runnable() {

					@Override
					public void run() {
						while (mSlidingDrawer.isMoving()) {
							try {
								Thread.sleep(50);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
						mHandler.post(new Runnable() {
							public void run() {
								if (!mSlidingDrawer.isOpened()) {
									mSlidingHandler.setBackgroundResource(R.drawable.transparent);
								}
							}
						});
					}
				});
				watchMovingThread.start();
			}
		});
	}

	private void initMessageView() {
		mMessageView.setMessageViewListener(new MessageListener() {

			@Override
			public void onMessageClick(MessageModel info) {
				unlock(getMessageRunnable(info), false);
			}
		});
		mContentView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				mMessageView.removeMessageView();
				return false;
			}
		});

		// mMessageView.addSMSMessage(2, System.currentTimeMillis(),
		// "18025310573");
		// mMessageView.addPhoneMessage(1, System.currentTimeMillis());
		// mMessageView.addMessage(null, mContext.getPackageName(),
		// R.string.app_message_tip,
		// System.currentTimeMillis(), null, null);
		// mMessageView.addMessage(null, "com.appssuper.toolbox",
		// R.string.app_message_tip,
		// System.currentTimeMillis(), null, null);
	}

	private void initPasswdView() {
		mPasswordType = LockPrefs.getPasswordType(mContext);
		if (mPasswordType == PasswordType.PATTERN_PASSWORD) {
			PatternPasswordView patternPasswordView = new PatternPasswordView(mContext);
			patternPasswordView.setOnPatternViewListener(new OnPatternViewListener() {
				@Override
				public void onPattern(PatternViewResult result) {
					if (result == PatternViewResult.UNLOCK) {
						mPasswdWindow.dismiss();
						mLockManager.setRunnableAfterUnLock(mUnLockRunnable);
						mLockManager.unLock();
					} else if (result == PatternViewResult.BACK) {
						mPasswdWindow.dismiss();
					} else if (result == PatternViewResult.EMS_CALL) {
						// emsCall();
					}
				}
			});
			patternPasswordView.setBackgroundResource(R.drawable.fifth_transparent);
			initPasswdWindow(patternPasswordView);
		} else if (mPasswordType == PasswordType.NUM_PASSWORD) {
			LockNumberView lockNumberView = new LockNumberView(mContext, LockNumberView.UNLOCK_PASSWORD);
			lockNumberView.setOnLockNumberListener(new OnLockNumberListener() {
				@Override
				public void OnLockNumber(int result) {
					if (result == LockNumberView.OK) {
						mPasswdWindow.dismiss();
						mLockManager.setRunnableAfterUnLock(mUnLockRunnable);
						mLockManager.unLock();
					} else if (result == LockNumberView.CANCELED) {
						mPasswdWindow.dismiss();
					} else if (result == LockNumberView.EMS_CALL) {
						// emsCall();
					}
				}
			});
			lockNumberView.setBackgroundResource(R.drawable.fifth_transparent);
			initPasswdWindow(lockNumberView);
		}
	}

	private void initPasswdWindow(View view) {
		mPasswdWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		mPasswdWindow.setAnimationStyle(R.style.AnimPopupBottom);
		mPasswdWindow.setBackgroundDrawable(new BitmapDrawable());
		mPasswdWindow.setOutsideTouchable(true);
		mPasswdWindow.setFocusable(true);
		mPasswdWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				showMainLockScreen();
			}
		});
	}

	private void showPasswdWindow() {
		mPasswdWindow.showAtLocation(mContentView, Gravity.LEFT | Gravity.TOP, 0, 0);
		hideMainLockScreen();
	}

	private void showLinkIcon(int position) {
		if (mWallpaperItems != null && mWallpaperItems.size() > 0 && position < mWallpaperItems.size()) {
			LockscreenCfgItem item = mWallpaperItems.get(position);
			if (!isDefaultWallpaper) {
				mLinkIconNPath = Config.CACHE_DIR + File.separator
						+ String.valueOf(item.getLinkIconNormal().hashCode());
				mLinkIconPPath = Config.CACHE_DIR + File.separator
						+ String.valueOf(item.getLinkIconPressed().hashCode());
				mLinkIconSPath = Config.CACHE_DIR + File.separator
						+ String.valueOf(item.getLinkIconSelected().hashCode());
				mUnlockLinkIv.setImageBitmap(mImageUtils.getBitmapDecodeFile(mLinkIconNPath));
			} else {
				mLinkIconNPath = item.getLinkIconNormal();
				mLinkIconPPath = item.getLinkIconPressed();
				mLinkIconSPath = item.getLinkIconSelected();
				mUnlockLinkIv.setImageResource(ResourceUtil.getDrawable(mContext, mLinkIconNPath));
			}
			mLink = item.getLink();
		}
	}

	public void ClearMessageView() {
		mMessageView.removeMessageView();
	}

	private void initData() {
		showTime();
		// 耗时操作200ms+
		new Thread(new Runnable() {
			@Override
			public void run() {
				getShortcutAppData();
			}
		}).start();
	}

	private void showTime() {
		Calendar c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);

		int hourFirst = hour / 10;
		int hourSecond = hour % 10;
		int minuteFirst = minute / 10;
		int minuteSecond = minute % 10;
		mDateTimeTv.setText(hourFirst + "" + hourSecond + ":" + minuteFirst + "" + minuteSecond);

		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		String week = "";
		switch (c.get(Calendar.DAY_OF_WEEK)) {
		case 1:
			week = "星期日";
			break;
		case 2:
			week = "星期一";
			break;
		case 3:
			week = "星期二";
			break;
		case 4:
			week = "星期三";
			break;
		case 5:
			week = "星期四";
			break;
		case 6:
			week = "星期五";
			break;
		case 7:
			week = "星期六";
			break;
		}
		mDateWeekTv.setText(month + "月" + day + "日   " + week);
	}

	private void getShortcutAppData() {
		boolean existFlashLight = false;
		Camera camera = null;
		if (!XiaomiUtils.isMeizu(mContext)) {
			try {
				camera = Camera.open();
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (camera != null) {
				try {
					Parameters params = camera.getParameters();
					List<String> list = params.getSupportedFlashModes();
                    existFlashLight = list != null && list.contains(Parameters.FLASH_MODE_TORCH);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					camera.release();
					camera = null;
				}
			}
		} else {// 魅族手机，都有闪光灯
			existFlashLight = true;
		}

		List<String> fixedList = new ArrayList<String>();
		fixedList.add("appmarket.screenlock.calculator");
		fixedList.add("appmarket.screenlock.camera");
		fixedList.add("appmarket.screenlock.flashlight");
		if (!existFlashLight) {
			fixedList.remove("appmarket.screenlock.flashlight");
		}

		mList = new ArrayList<AppModel>();

		for (String pkg : fixedList) {
			AppModel appInfo = new AppModel();
			appInfo.setPkgName(pkg);
			appInfo.setFixed(true);
			mList.add(appInfo);
		}
		AppModel appInfo = new AppModel();
		appInfo.setPkgName(mContext.getPackageName());
		appInfo.setClassName(LoadingActivity.class.getName());
		appInfo.setFixed(true);
		mList.add(appInfo);
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				refreshView();
			}
		});
	}

	private void refreshView() {
		mAdapter = new ShortcutAppMainLockAdapter(mContext);
		mAdapter.setList(mList);
		mAdapter.setShortcutListener(new OnShortcutListener() {
			@Override
			public void OnShortcutItemClick(AppModel model) {
				if (model.getPkgName().equals("appmarket.screenlock.flashlight")) {
					startFlashLight();
				} else if (model.getPkgName().equals("appmarket.screenlock.camera")) {
					AppMarketApplication.sIsPauseLocked = true;
					if (mPasswordType == PasswordType.NO_PASSWORD) {
						unlock(getCameraRunnable(false), false);
					} else {
						unlock(getCameraRunnable(true), true);
					}
				} else if (model.getPkgName().equals("appmarket.screenlock.calculator")) {
					AppMarketApplication.sIsPauseLocked = true;
					if (mPasswordType == PasswordType.NO_PASSWORD) {
						unlock(getCalculatorRunnable(false), false);
					} else {
						unlock(getCalculatorRunnable(true), true);
					}
				} else {
					unlock(getShortcutRunnable(model), false);
				}
			}
		});
		mSlidingContent.setAdapter(mAdapter);
	}

	private void unlock(Runnable runnable, boolean forceClose) {
		mUnLockRunnable = runnable;
		if (mPasswordType == PasswordType.NO_PASSWORD) {
			mLockManager.setRunnableAfterUnLock(mUnLockRunnable);
			mLockManager.unLock(false);
		} else {
			if (!forceClose) {
				showPasswdWindow();
			} else {
				mLockManager.setRunnableAfterUnLock(mUnLockRunnable);
				mLockManager.unLock(true);
			}
		}
	}

	private Runnable getInitSettingRunnable() {
		Runnable runnable = null;
		if (!LockPrefs.isInitLockSetting(mContext)) {
			if (LockPrefs.isFirstUnlock(mContext)) {
				// LockPrefs.setFirstUnlock(mContext, false);
				// runnable = new Runnable() {
				// @Override
				// public void run() {
				// startInitSettingActivity();
				// }
				// };
			} else if ("XX".equals(NetTools.getChannelType(mContext))) {
				// 线下包触发
				if (LockPrefs.isFirstSimInUnlock(mContext)) {
					if (SimUtil.isSimIn(mContext)) {
						LockPrefs.setFirstSimInUnlock(mContext, false);
						runnable = new Runnable() {
							@Override
							public void run() {
								startInitSettingActivity();
							}
						};
					}
				}
			}
		}
		return runnable;
	}

	private Runnable getLinkRunnable(final Link link) {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				startLinkActivity(link);
			}
		};
		return runnable;
	}

	private Runnable getMessageRunnable(final MessageModel info) {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				startMessageActivity(info);
			}
		};
		return runnable;
	}

	private Runnable getCameraRunnable(final boolean hasPassword) {
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				startCamera();
				if (hasPassword) {
					new WatchCameraThread().start();
				}
			}

		};
		return runnable;
	}

	class WatchCameraThread extends Thread {

		@Override
		public void run() {
			try {
				AppMarketApplication.sIsPauseLocked = true;
				Thread.sleep(4000);
				boolean isCameraOpened = true;
				while (!mLockManager.isLocked() && isCameraOpened) {
					Thread.sleep(50);
					if (XiaomiUtils.isMeizu(mContext)) {// 针对魅族手机做的处理
						ComponentName topComponent = getRunningTopPkgApp(mContext);
						Set<String> cameraPkgs = getCameraPackageName();
						if (cameraPkgs != null && topComponent != null
								&& cameraPkgs.contains(topComponent.getPackageName())) {
							isCameraOpened = true;
						} else {
							isCameraOpened = isCameraOpened();
						}
					} else {
						isCameraOpened = isCameraOpened();
					}
				}
			} catch (Exception e) {
				LogUtil.w(TAG, "WatchCameraThread error", e);
			}
			mHandler.post(new Runnable() {

				@Override
				public void run() {
					if (!mLockManager.isLocked()) {
						mLockManager.lock();
					}
				}
			});
		}
	}

	private Runnable getCalculatorRunnable(final boolean hasPassword) {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				Intent intent = new Intent(mContext, CalculatorActivity.class);
				if (hasPassword) {
					intent.putExtra(CalculatorActivity.EXTRA_IN_ACTIVITY, CalculatorActivity.FROM_LOCK_SCREEN);
				}
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				mContext.startActivity(intent);
			}
		};
		return runnable;
	}

	private Runnable getShortcutRunnable(final AppModel info) {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				intent.setClassName(mContext, info.getClassName());
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				mContext.startActivity(intent);
			}
		};
		return runnable;
	}

	private ComponentName getRunningTopPkgApp(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);
		List<RunningTaskInfo> infoList = am.getRunningTasks(1);
		if (infoList.isEmpty()) {
			return null;
		}
		RunningTaskInfo info = infoList.get(0);
		return info.topActivity;
	}

	private Set<String> getCameraPackageName() {
		Set<String> packageNames = new HashSet<String>();
		Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
		List<ResolveInfo> resolveInfo = mContext.getPackageManager().queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		for (ResolveInfo ri : resolveInfo) {
			packageNames.add(ri.activityInfo.packageName);
			LogUtil.i(TAG, "camera packageName =" + ri.activityInfo.packageName);
		}
		if (packageNames == null || packageNames.size() == 0) {
			return null;
		}
		return packageNames;
	}

	private void startCamera() {
		releaseCamera();
		// 启动照相机
		Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); 
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		mContext.startActivity(intent);
	}

	private void startFlashLight() {
		if (mIsLightOpen) {
			closeLight();
		} else {
			openLight();
		}
		mVibrator.vibrate(mPattern, -1);
	}

	private void openLight() {
		if (mCamera == null) {
			try {
				mCamera = Camera.open();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (mCamera != null && !mIsLightOpen) {
			try {
				Parameters params = mCamera.getParameters();
				List<String> list = params.getSupportedFlashModes();
				if (list != null && list.contains(Parameters.FLASH_MODE_TORCH)) {
					params.setFlashMode(Parameters.FLASH_MODE_TORCH);
					mCamera.setParameters(params);
					mCamera.startPreview();
					mIsLightOpen = true;
				} else {
					Toast.makeText(mContext.getApplicationContext(), R.string.device_no_support_flash_light,
							Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void closeLight() {
		if (mCamera == null) {
			mIsLightOpen = false;
			return;
		}
		try {
			Parameters closeParameters = mCamera.getParameters();
			closeParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
			mCamera.setParameters(closeParameters);
			mCamera.stopPreview();
			mIsLightOpen = false;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void releaseCamera() {
		if (null != mCamera) {
			mIsLightOpen = false;
			mCamera.release();
			mCamera = null;
		}
	}

	private void startInitSettingActivity() {
		Intent intent = new Intent(mContext, InitSettingDialogActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(intent);
	}

	private void startLinkActivity(Link link) {
		if (link == null) {
			return;
		}
		if (LinkType.App == link.getType()) {
			Intent detail = new Intent(mContext, AppDetailActivity.class);
			detail.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			detail.putExtra(AppDetailActivity.EXTRA_NAME, link.getTitle());
			detail.putExtra(AppDetailActivity.EXTRA_PKG, link.getUrl());
			detail.putExtra(AppDetailActivity.EXTRA_SOURCE,
					new ApkSource("unlock", link.getUrl(), null, null, null, null, null).toSourceString());
			mContext.startActivity(detail);

		} else if (LinkType.Cards == link.getType()) {
			if ("essential".equals(link.getUrl())) {
				Intent intent = new Intent(mContext, PhoneEssentialActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				mContext.startActivity(intent);
			} else {
				Intent card = new Intent(mContext, CardPageActivity.class);
				card.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				card.putExtra(CardPageActivity.EXTRA_TITLE, link.getTitle());
				card.putExtra(CardPageActivity.EXTRA_PATH, link.getUrl());
				mContext.startActivity(card);
			}
		} else if (LinkType.WebView == link.getType()) {
			Intent detail = new Intent(mContext, WebViewActivity.class);
			detail.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			detail.putExtra(WebViewActivity.EXTRA_TITLE, link.getTitle());
			detail.putExtra(WebViewActivity.EXTRA_URL, link.getUrl());
			mContext.startActivity(detail);
		}
	}

	private void startMessageActivity(MessageModel info) {
		if (info == null) {
			return;
		}
		try {
			if (info.getAppName() != null && "toolbox_phone".equals(info.getAppName())) {
				// 系统 通话记录 界面
				Intent intent = new Intent();
				intent.setAction("android.intent.action.DIAL");
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				mContext.startActivity(intent);

			} else if (info.getAppName() != null && "toolbox_sms".equals(info.getAppName())) {
				// 流程修改为：启动最后一个未读短信的编辑界面
				if (info.getExtra() != null) {
					Uri uri = Uri.parse("smsto:" + info.getExtra());
					Intent intent = new Intent("android.intent.action.SENDTO", uri);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					mContext.startActivity(intent);
				}
			} else {
				// 其他软件
				if (info.getNotification() != null) {
					PendingIntent pendingIntent = info.getNotification().contentIntent;
					pendingIntent.send();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_lock_setting_btn:
			unlock(new Runnable() {
				@Override
				public void run() {
					Intent intent = new Intent();
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					if (!isTopActivity(BeautifulLockerSettingActivity.class.getName())) {
						intent.setClass(mContext, BeautifulLockerSettingActivity.class);
						mContext.startActivity(intent);
					}
				}
			}, false);
			break;
		default:
			break;
		}
	}

	private boolean isTopActivity(String acName) {
		if (!TextUtils.isEmpty(acName)) {
			return acName.equals(mTopActivityName);
		} else {
			return false;
		}
	}

	class MyReceiver extends BroadcastReceiver {

		@SuppressLint("NewApi")
		@Override
		public void onReceive(Context context, Intent intent) {
			// 判断它是否是为电量变化的Broadcast Action
			if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
				int status = intent.getIntExtra("status", -1);
				if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
					mChargingIv.setVisibility(View.VISIBLE);
				} else {
					mChargingIv.setVisibility(View.GONE);
				}
				int level = intent.getIntExtra("level", 0);
				int scale = intent.getIntExtra("scale", 100);
				mElectricQuantityTv.setText(level * 100 / scale + "%");
				mChargingPv.setProgress(level * 100 / scale);
			} else if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
				showTime();
				if (mMessageView != null) {
					mMessageView.updateView();
				}
			} else if (LockerService.TOOLBOX_RECIVE_SMS_ACTION.equals(intent.getAction())) {
				// 短信处理
				int count = intent.getIntExtra(LockerService.SMS_WATCHER_UNREAD_COUNT, 0);
				long date = intent.getLongExtra(LockerService.SMS_WATCHER_DATE, 0);
				String address = intent.getStringExtra(LockerService.SMS_WATCHER_ADDRESS);
				if (count > 0 && address != null) {
					mMessageView.addSMSMessage(count, date, address);
				}
			} else if (LockerService.TOOLBOX_RECIVE_CALL_ACTION.equals(intent.getAction())) {
				int count = intent.getIntExtra(LockerService.CALL_WATCHER_UNREAD_COUNT, 0);
				long date = intent.getLongExtra(LockerService.CALL_WATCHER_DATE, 0);
				if (count > 0) {
					mMessageView.addPhoneMessage(count, date);
				}
			} else if (SystemNotificationListener.ACTION_OBTAIN_ACTIVE_NOTIFICATIONS.equals(intent.getAction())) {
				StatusBarNotification sbn = intent
						.getParcelableExtra(SystemNotificationListener.NOTIFICATION_POSTED);
				long postTime = sbn.getPostTime();
				// if(sbn.getPackageName().equals("com.tencent.mobileqq")){
				// Bundle bundle = sbn.getNotification().extras;
				// String content = bundle.getString("android.text");
				// mMessageView.addMessage(null, sbn.getPackageName(), content,
				// postTime, null,sbn.getNotification());
				// }else{
				mMessageView.addMessage(null, sbn.getPackageName(), R.string.app_message_tip, postTime, null,
						sbn.getNotification());
				// }

				wakeLockScreen();
			} else if (SystemNotificationService.ACTION_ACTIVE_SERVICE_NOTIFICATIONS.equals(intent.getAction())) {
				Notification notification = intent
						.getParcelableExtra(SystemNotificationService.NOTIFICATION_SERVICE);
				mMessageView.addMessage(null, notification.contentView.getPackage(), R.string.app_message_tip,
						System.currentTimeMillis(), null, notification);
				wakeLockScreen();
			}
		}
	}

	private void wakeLockScreen() {
		if (mWakeLock != null) {
			if (!pm.isScreenOn()) {
				lockHandler.sendEmptyMessageDelayed(11, 5000);
			}
			// 点亮屏幕
			mWakeLock.acquire(5000);
		}
	}

	public void removeMessage() {
		lockHandler.removeMessages(11);
	}

	private static class MyHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 11) {
				if (mPolicyManager.isAdminActive(mComponentName)) {
					try {
						mPolicyManager.lockNow();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

	}

	private void registerReceiver() {
		IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		intentFilter.addAction(Intent.ACTION_TIME_TICK);
		intentFilter.addAction(LockerService.TOOLBOX_RECIVE_SMS_ACTION);
		intentFilter.addAction(LockerService.TOOLBOX_RECIVE_CALL_ACTION);
		intentFilter.addAction(SystemNotificationListener.ACTION_CANCEL_NOTIFICATION);
		intentFilter.addAction(SystemNotificationListener.ACTION_OBTAIN_ACTIVE_NOTIFICATIONS);
		intentFilter.addAction(SystemNotificationService.ACTION_ACTIVE_SERVICE_NOTIFICATIONS);
		mReceiver = new MyReceiver();
		mContext.registerReceiver(mReceiver, intentFilter);
	}

	public void unregisterReceiver() {
		if (mContext != null && mReceiver != null) {
			try {
				mContext.unregisterReceiver(mReceiver);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (mWakeLock != null) {
			if (mWakeLock.isHeld()) {
				mWakeLock.release();
			}
			mWakeLock = null;
		}
	}

	public void openSliding(boolean isOpen) {
		if (mSlidingDrawer != null) {
			if (isOpen) {
				if (!mSlidingDrawer.isOpened()) {
					mSlidingDrawer.animateClose();
				}
			} else {
				if (mSlidingDrawer.isOpened()) {
					mSlidingDrawer.animateClose();
				}
			}
		}
	}

	public void showMainLockScreen() {
		mMainLockScreenLy.setVisibility(View.VISIBLE);
		mMainLockBottomLy.setVisibility(View.VISIBLE);
	}

	public void hideMainLockScreen() {
		mMainLockScreenLy.setVisibility(View.GONE);
		mMainLockBottomLy.setVisibility(View.GONE);
	}

	public interface OnSlidingDrawerOpenListener {
		void onSlidingDrawerChange(boolean isOpen);
	}

	public PagerAdapter getWallpaperAdapter() {
		mWallpaperItems = getWallpaperItem(mContext);
		if (mWallpaperItems != null && mWallpaperItems.size() > 0) {
			isDefaultWallpaper = false;
			return new WallpaperAdapter(mContext, mWallpaperItems);
		} else {
			mWallpaperItems = getDefWallpaperItem(mContext);
			isDefaultWallpaper = true;
			return new WallpaperDefAdapter(mContext, mWallpaperItems);
		}
	}

	public class WallpaperAdapter extends PagerAdapter {
		private Context mContext;
		private List<LockscreenCfgItem> mList;

		public WallpaperAdapter(Context context, List<LockscreenCfgItem> list) {
			mContext = context;
			mList = list;
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public View instantiateItem(ViewGroup container, final int position) {

			final LockscreenCfgItem item = mList.get(position % mList.size());
			LayoutInflater li = LayoutInflater.from(mContext);
			View view = li.inflate(R.layout.screenlock_wallpaper_layout, container, false);
			ImageView wallpaperView = view.findViewById(R.id.screenlock_wallpaper_image);
			String wallpaperPath = Config.CACHE_DIR + File.separator + String.valueOf(item.getImage().hashCode());
			wallpaperView.setImageBitmap(mImageUtils.getBitmapDecodeFile(wallpaperPath));

			container.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			return view;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
	}

	public class WallpaperDefAdapter extends PagerAdapter {
		private Context mContext;
		private List<LockscreenCfgItem> mList;

		public WallpaperDefAdapter(Context context, List<LockscreenCfgItem> list) {
			mContext = context;
			mList = list;
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public View instantiateItem(ViewGroup container, final int position) {

			final LockscreenCfgItem item = mList.get(position % mList.size());
			LayoutInflater li = LayoutInflater.from(mContext);
			View view = li.inflate(R.layout.screenlock_wallpaper_layout, container, false);
			ImageView icon = view.findViewById(R.id.screenlock_wallpaper_image);
			icon.setImageBitmap(mImageUtils.getBitmapDecodeResForWallpaper(mContext,
					ResourceUtil.getDrawable(mContext, item.getImage())));

			container.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			return view;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
	}

	/**
	 * 获取当天显示且已下载好的壁纸图片
	 * 
	 * @return
	 */
	public List<LockscreenCfgItem> getWallpaperItem(Context context) {
		List<LockscreenCfgItem> wallpaperPathList = new ArrayList<LockscreenCfgItem>();
		LockscreenCfg mLockscreenCfg = LockScreenConfig.getLockscreenConfig(context);
		if (mLockscreenCfg == null) {
			return wallpaperPathList;
		} else {
			List<LockscreenCfgItem> lockscreenCfgItems = mLockscreenCfg.getConfig();
			if (lockscreenCfgItems == null) {
				return wallpaperPathList;
			} else {
				long currentTime = System.currentTimeMillis();
				for (LockscreenCfgItem item : lockscreenCfgItems) {
					if (item == null) {
						continue;
					}
					if (TextUtils.isEmpty(item.getImage()) || TextUtils.isEmpty(item.getLinkIconNormal())
							|| TextUtils.isEmpty(item.getLinkIconPressed())
							|| TextUtils.isEmpty(item.getLinkIconSelected())) {
						continue;
					}
					if (currentTime > castServerTime(item.getStartTime())
							&& currentTime < castServerTime(item.getEndTime())) {
						String wallpaperPath = Config.CACHE_DIR + File.separator
								+ String.valueOf(item.getImage().hashCode());
						String linkIconNormalPath = Config.CACHE_DIR + File.separator
								+ String.valueOf(item.getLinkIconNormal().hashCode());
						String linkIconPressedPath = Config.CACHE_DIR + File.separator
								+ String.valueOf(item.getLinkIconPressed().hashCode());
						String linkIconSelectedPath = Config.CACHE_DIR + File.separator
								+ String.valueOf(item.getLinkIconSelected().hashCode());
						File wallpaperFile = new File(wallpaperPath);
						File iconNormalFile = new File(linkIconNormalPath);
						File iconPressedFile = new File(linkIconPressedPath);
						File iconSelectedFile = new File(linkIconSelectedPath);
						if (wallpaperFile.exists() && iconNormalFile.exists() && iconPressedFile.exists()
								&& iconSelectedFile.exists()) {
							wallpaperPathList.add(item);
						}
					}
				}
			}
		}
		return wallpaperPathList;
	}

	// 服务器获取的时间为下午一点 yyyy-MM-dd 13:00:00， 转换为0点
	public long castServerTime(long time) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		String dateStr = format.format(time);
		try {
			Date date = format.parse(dateStr);
			return date.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return time;
	}

	/**
	 * 获取默认壁纸图片
	 * 
	 * @return
	 */
	public List<LockscreenCfgItem> getDefWallpaperItem(Context context) {
		List<LockscreenCfgItem> wallpaperPathList = new ArrayList<LockscreenCfgItem>();
		LockscreenCfg mLockscreenCfg = LockScreenConfig.getDefLockscreenConfig(context);
		if (mLockscreenCfg == null) {
			return wallpaperPathList;
		} else {
			List<LockscreenCfgItem> lockscreenCfgItems = mLockscreenCfg.getConfig();
			if (lockscreenCfgItems == null) {
				return wallpaperPathList;
			} else {
				for (LockscreenCfgItem item : lockscreenCfgItems) {
					if (item == null) {
						continue;
					}
					if (TextUtils.isEmpty(item.getImage()) || TextUtils.isEmpty(item.getLinkIconNormal())
							|| TextUtils.isEmpty(item.getLinkIconPressed())
							|| TextUtils.isEmpty(item.getLinkIconSelected())) {
						continue;
					}
					wallpaperPathList.add(item);
				}
			}
		}
		return wallpaperPathList;
	}

	public void changeWallpaper() {
		if (mWallpaperViewpager != null && mWallpaperViewpager.getAdapter() != null) {
			mCurrentPageIndex++;
			if (mCurrentPageIndex >= mWallpaperViewpager.getAdapter().getCount()) {
				mCurrentPageIndex = 0;
			}
			mWallpaperViewpager.setCurrentItem(mCurrentPageIndex);
			showLinkIcon(mCurrentPageIndex);
		}
	}

	private static boolean isCameraOpened() {
		boolean isOpened = false;
		Camera camera = null;
		try {
			camera = Camera.open();
		} catch (Exception e) {
			isOpened = true;
		}
		if (!isOpened) {
			camera.release();
			camera = null;
		}
		return isOpened;
	}
}
